package org.puresource.web.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

/**
 * spring mvc配置，自动扫描controller包
 * @author Young
 *
 */
@Configuration
@EnableWebMvc
@ComponentScan(basePackages="org.puresource.web.controller")
@Import(WebApplicationConfig.class)
public class SpringMvcConfig extends WebMvcConfigurerAdapter{
	
	/**
	 * 视图渲染交给InternalResourceViewResolver
	 * @return
	 */
	@Bean
	public ViewResolver viewResolver() {
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		viewResolver.setPrefix("/WEB-INF/views/");
		viewResolver.setSuffix(".jsp");
		return viewResolver;
	}
	
	/**
	 * json转换器，使用fastjson
	 */
	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		FastJsonHttpMessageConverter fastJson = new FastJsonHttpMessageConverter();
		List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
		//避免IE返回时出现下载提示
		supportedMediaTypes.add(MediaType.valueOf("text/html;charset=UTF-8"));
		supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
		fastJson.setSupportedMediaTypes(supportedMediaTypes);
		converters.add(fastJson);
	}

//	/**
//	 * 静态资源交给default servlet处理
//	 */
//	@Override
//	public void configureDefaultServletHandling(
//			DefaultServletHandlerConfigurer configurer) {
//		configurer.enable();
//	}

	/**
	 * 使用ResourceHttpRequestHandler处理静态资源
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		//静态资源相对路径
		registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
	}
}
